package com.hngy.xpq.android_practice.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.hngy.xpq.android_practice.bean.Merchant;
import com.hngy.xpq.android_practice.utils.MerchantOrder;

public class SQLiteMerchant extends SQLiteOpenHelper {         //<商家>
    private SQLiteDatabase sqLiteDatabase;
    public SQLiteMerchant(Context context) {
        super(context, MerchantOrder.DATABASE_DATA, null, MerchantOrder.DATABASE_INS);
        sqLiteDatabase = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + MerchantOrder.DATABASE_TABLE + "("
                + MerchantOrder.NOTEPAD_ID + " integer primary key autoincrement,"
                + MerchantOrder.NOTEPAD_NAME + " VARCHAR(50),"
                + MerchantOrder.NOTEPAD_KEY + " VARCHAR(50),"
                + MerchantOrder.NOTEPAD_PHONE + " VARCHAR(20),"
                + MerchantOrder.NOTEPAD_TIME + " VARCHAR(20),"
                + MerchantOrder.NOTEPAD_ADD + " VARCHAR(50),"
                + MerchantOrder.NOTEPAD_DES + " VARCHAR(200))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public boolean Merchant_add(Merchant m){
        ContentValues values = new ContentValues();
        values.put(MerchantOrder.NOTEPAD_NAME,m.getName());
        values.put(MerchantOrder.NOTEPAD_KEY,m.getKey());
        values.put(MerchantOrder.NOTEPAD_PHONE,m.getPhone());
        values.put(MerchantOrder.NOTEPAD_TIME,MerchantOrder.getTimeDate());
        values.put(MerchantOrder.NOTEPAD_ADD,m.getAdd());
        values.put(MerchantOrder.NOTEPAD_DES,m.getDes());
        return
                sqLiteDatabase.insert(MerchantOrder.DATABASE_TABLE,null,values)>0;
    }

    public Merchant dl_merchant(String phone , String key){
        Merchant m = null;
        try{
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + MerchantOrder.DATABASE_TABLE +
                    " where " +  MerchantOrder.NOTEPAD_PHONE +
                    " = " + phone  , null,null);
            if (cursor.moveToNext()){
                m = new Merchant();
                m.setName(cursor.getString(cursor.getColumnIndex(MerchantOrder.NOTEPAD_NAME)));
                m.setKey(cursor.getString(cursor.getColumnIndex(MerchantOrder.NOTEPAD_KEY)));
                m.setPhone(cursor.getString(cursor.getColumnIndex(MerchantOrder.NOTEPAD_PHONE)));
                m.setAdd(cursor.getString(cursor.getColumnIndex(MerchantOrder.NOTEPAD_ADD)));
                m.setDes(cursor.getString(cursor.getColumnIndex(MerchantOrder.NOTEPAD_DES)));
            } else {
                System.out.println("连接异常!!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }
}
